package org.common.utils.database.change;

import org.common.utils.consumer.ConsumerConfig;
import org.common.utils.consumer.ConsumerGroup;
import org.common.utils.consumer.ConsumerGroupFactory;
import org.common.utils.database.access.DataAccessTool;

import java.util.List;

/**
 * @author zhouzhibing
 * @date 2025/8/5
 */
public class DataChangeManager {
    /**
     * 单例对象
     */
    private static final DataChangeManager INSTANCE = new DataChangeManager();
    /**
     * 插入消费组
     */
    private final ConsumerGroup insertConsumerGroup;
    /**
     * 删除消费组
     */
    private final ConsumerGroup deleteConsumerGroup;
    /**
     * 更新消费组
     */
    private final ConsumerGroup updateConsumerGroup;


    private DataChangeManager() {
        ConsumerConfig insertConfig = ConsumerConfig.newBuilder().setCount(1).setName("DataChangeManager-insert").setHandler(this::doInsertHandler).build();
        insertConsumerGroup = ConsumerGroupFactory.ofQueue(insertConfig);

        ConsumerConfig deleteConfig = ConsumerConfig.newBuilder().setCount(1).setName("DataChangeManager-delete").setHandler(this::doDeleteHandler).build();
        deleteConsumerGroup = ConsumerGroupFactory.ofQueue(deleteConfig);

        ConsumerConfig updateConfig = ConsumerConfig.newBuilder().setCount(1).setName("DataChangeManager-update").setHandler(this::doUpdateHandler).build();
        updateConsumerGroup = ConsumerGroupFactory.ofQueue(updateConfig);
    }

    public static DataChangeManager get() {
        return INSTANCE;
    }

    /**
     * 添加插入消费组
     * @param entity 实体对象
     */
    public void insert(Object entity) {
        insertConsumerGroup.add(entity);
    }

    /**
     * 添加删除消费组
     * @param entity 实体对象
     */
    public void delete(Object entity) {
        deleteConsumerGroup.add(entity);
    }

    /**
     * 添加更新消费组
     * @param entity 实体对象
     */
    public void update(Object entity) {
        updateConsumerGroup.add(entity);
    }

    public void doInsertHandler(String name , Object entity) {
        System.out.println("doInsertHandler name = " + name + ", entity = " + entity);
    }

    public void doDeleteHandler(String name , Object entity) {
        System.out.println("doDeleteHandler name = " + name + ", entity = " + entity);
    }

    public void doUpdateHandler(String name , Object entity) {
        if(entity instanceof List<?> list) {
            DataAccessTool.get().getDataAccess().update(list);
        } else {
            DataAccessTool.get().getDataAccess().update(entity);
        }
//        System.out.println("doUpdateHandler name = " + name + ", entity = " + entity);
    }
}
